package com.common.utils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

public class MD5Utils {
  private static final String SALT = "1qazxsw2";

  private static final String ALGORITH_NAME = "md5";

  private static final int HASH_ITERATIONS = 2;

  public static String encrypt(String pswd) {
    String newPassword =
        new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
    return newPassword;
  }

  public static String encrypt(String username, String pswd) {
    String newPassword =
        new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT), HASH_ITERATIONS)
            .toHex();
    return newPassword;
  }

  /**
   * 32位小写 MD5 加密
   *
   * @param string
   * @return
   */
  public static String md5Encrypt32Lower(String string) {
    return md5Encrypt32(string).toLowerCase();
  }

  public static String md5Encrypt32(String string) {
    if (StringUtils.isBlank(string)) {
      return "";
    }
    byte[] hash;
    try {
      hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException("Huh, MD5 should be supported?", e);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("Huh, UTF-8 should be supported?", e);
    }

    StringBuilder hex = new StringBuilder(hash.length * 2);
    for (byte b : hash) {
      if ((b & 0xFF) < 16) {
        hex.append("0");
      }
      hex.append(Integer.toHexString(b & 0xFF));
    }
    return hex.toString();
  }

  /***
   * 远程url文件md5
   * @param url
   * @return
   */
  public static String md5UrlEncrypt(String url) {
    InputStream inputStream = null;
    String md5 = "";
    try {
      URLConnection connection = new URL(url).openConnection();
      inputStream = connection.getInputStream();
      md5 = DigestUtils.md5Hex(inputStream);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
    return md5;
  }

  public static void main(String[] args) {
    String strName = "test";
    String password = "123456";
    System.out.println(MD5Utils.encrypt(strName, password));
  }
}
